package kafkfa.producerconsumer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

public class KafkaProducerDemo {

    public static void main(String[] args) {
        String bootstrapServers = "192.168.0.228:9092";
        String topicName = "quickstart-events";

        // 配置生产者属性
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());

        // 可选配置
        props.put(ProducerConfig.ACKS_CONFIG, "all"); // 所有副本都确认
        props.put(ProducerConfig.RETRIES_CONFIG, 3);  // 失败重试次数
        props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true); // 幂等性写入

        // 创建生产者
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(props)) {
            for (int i = 0; i < 10; i++) {
                String message = "Hello Kafka Message - " + i;

                ProducerRecord<String, String> record = new ProducerRecord<>(topicName, message);

                // 发送消息（同步方式）
                RecordMetadata metadata = producer.send(record).get();

                System.out.printf("Sent message: %s to topic %s partition %d with offset %d%n",
                        message, metadata.topic(), metadata.partition(), metadata.offset());
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
